<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\BaseController;
use App\Http\Events\Admin\AdminEvent;
use App\Http\Model\Admin\Role;
use App\Http\Model\Admin\RoleUser;
use App\Http\Model\Admin\User;
use Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;

class UserController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = new User();
        $user_data = $user->findAllByPaginate();
        return view('admin.user', ['user_list' => $user_data]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $role = new Role();
        $role_list = $role->findAllValid();
        return view('admin.user_create', ['role_list' => $role_list]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = Input::except('_token');

        $validator = $this->formValidator($input, Config::get('admin.user.rules'), Config::get('admin.user.message'));
        if ($validator->passes()) {
            $one = (new User())->findOneByName($input['name']);
            if ($one && $one->name) {
                return back()->with('errors', Config::get('admin.errors.repeat'));
            } else {
                $input['password'] = Crypt::encrypt($input['password']);
                $re = (new User())->createNew($input);

                if ($re) {
                    event(new AdminEvent('create_user', $re));
                    if(count($input['menu_ids'])) {
                        $role_users = [];
                        foreach ($input['menu_ids'] as $item) {
                            array_push($role_users, [
                                'user_id' => $re['id'],
                                'role_id' => $item
                            ]);
                        }
                        $role_re = (new RoleUser())->createBatch($role_users);
                    }
                    return redirect('admin/user');
                } else {
                    return back()->with('errors', Config::get('admin.errors.createFail'));
                }
            }
        } else {
            return back()->withErrors($validator);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $role = new Role();
        $role_list = $role->findAllValid();
        $user = new User();
        $one = $user->findOneById($id);
        $roles = $one->roles;
        $related_roles = [];
        if ($roles) {
            foreach ($roles as $item) {
                array_push($related_roles, $item['id']);
            }
        }
        $one['password'] = Crypt::decrypt($one['password']);
        return view('admin.user_edit', [
            'user_info' => $one,
            'role_list' => $role_list,
            'related_roles' => $related_roles
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $role_ids = isset(Input::all()['role_ids']) ? Input::all()['role_ids'] : [];
        $input = Input::except('_token', '_method', 'role_ids');

        $validator = $this->formValidator($input, Config::get('admin.user.rules'), Config::get('admin.user.message'));
        if ($validator->passes()) {
            $input['password'] = Crypt::encrypt($input['password']);
            $old_user = (new User())->findOneById($id);
            $old_user_roles = $old_user->roles;
            $old_roles = [];
            if (count($old_user_roles)) {
                foreach ($old_user_roles as $item) {
                    array_push($old_roles, $item['id']);
                }
            }
            $re = (new User())->updateOneById($id, $input);
            $old = $old_user->makeVisible('password')->toArray();
            $old['roles'] = $old_roles;
            $input['roles'] = $role_ids;
            if ($re) {
                event(new AdminEvent('edit_user', $input, $old));
                if ($role_ids) {
                    $obj = [];
                    foreach ($role_ids as $item) {
                        array_push($obj, [
                            'user_id' => $id,
                            'role_id' => $item
                        ]);
                    }
                    //删除
                    $delete_rs = (new RoleUser())->deleteBatch($id);
                    if ($delete_rs) {
                        //添加
                        $add_rs = (new RoleUser())->createBatch($obj);
                        if ($add_rs) {
                            return redirect('admin/user');
                        } else {
                            return back()->with('errors', Config::get('admin.errors.editFail'));
                        }
                    } else {
                        return back()->with('errors', Config::get('admin.errors.editFail'));
                    }
                }
                return redirect('admin/user');
            } else {
                return back()->with('errors', Config::get('admin.errors.editFail'));
            }
        } else {
            return back()->withErrors($validator);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $old_obj = (new User())->findOneById($id);
        $rs = (new User())->deleteById($id);
        if ($rs) {
            event(new AdminEvent('remove_user', $old_obj, ''));
            return redirect('admin/user');
        }
    }
}
